# -*- coding: utf-8 -*-
# @Time    : 2022/11/16 15:18
# @Author  : yangyuexiong
# @Email   : yang6333yyx@126.com
# @File    : main.py
# @Software: PyCharm


from openpyxl import Workbook

from commands.app_commands.Excel.excel_base.main import ExcelHandle, del_range_tuple


class ExcelDeleteHandle(ExcelHandle):
    """删除"""

    def __init__(self, excel_path=None):
        super(ExcelDeleteHandle, self).__init__(excel_path=excel_path)

        self.del_range_dict = {
            "a_line": self.del_a_line,
            "one_column": self.del_one_column,
            "all": self.del_all
        }

    def del_a_line(self, sheet, row_num, **kwargs):
        """
        删除一行数据
        :param sheet: sheet对象
        :param row_num: 行号
        :param kwargs:
        {
            "is_save_as":False,
            "new_path":""
        }
        :return:
        """

        print('=== del_a_line ===')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')
        max_row = sheet.max_row
        # print(max_row)
        if int(row_num) > max_row:
            msg = f'删除失败：删除行号大于最大行数 {max_row}'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        sheet.delete_rows(int(row_num))
        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def del_one_column(self, sheet, column_num, **kwargs):
        """
        删除一列数据
        :param sheet: sheet对象
        :param column_num: 列号
        :param kwargs:
        :return:
        """

        print('=== del_one_column ===')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        sheet_columns = list(sheet.columns)
        col_index = None
        col_y = None
        for index, i in enumerate(sheet_columns, 1):
            before_cell = i[0].coordinate
            if before_cell == f'{column_num}1':
                # print(i)
                col_index = index
                col_y = column_num
                break

        # print(col_index, col_y)

        if not col_index:
            msg = f'删除失败：删除列号：{column_num} 不存在或数据为空'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        sheet.delete_cols(col_index)
        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def del_all(self, sheet, **kwargs):
        """
        删除全表
        :param sheet:
        :param kwargs:
        :return:
        """

        print('=== del_all ===')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')
        # print(sheet)
        sheet_title = sheet.title
        # print(f"sheet_title:{sheet_title}")
        self.wb.remove(sheet)
        self.wb.create_sheet(sheet_title)
        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def excel_del(self, sheet_name=None, del_range=None, **kwargs):
        """
        删除
        :param sheet_name: sheet名称
        :param del_range: 范围类型
        :param kwargs: 对应范围类型的扩展参数
        a_line:
            行号
            {
                "row_num":"1"
            }
        one_column:
            列号
            {
                "column_num":"A",
            }
        all:
            全表
            {}
        :return:
        """

        try:
            if isinstance(self.wb, Workbook):
                self.wb.save(self.excel_path)
                # print(f"读取:{self.excel_path.split('/')[-1]}")

                if del_range not in del_range_tuple:
                    msg = f'删除范围错误:{del_range}'
                    print(msg)
                    self.throw['status'] = False
                    self.throw['message'] = msg
                    return self.throw

                if not self.check_sheet_name(sheet_name):
                    return self.throw

                sheet = self.get_sheet(sheet_name)
                kwargs['sheet'] = sheet

                del_func = self.del_range_dict.get(del_range)
                del_func(**kwargs)
                return self.throw

        except BaseException as e:
            self.return_error_file()
            return self.throw
